package cn.gson.oasys.common.Interceptor;

import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import cn.gson.oasys.common.Tool;
import cn.gson.oasys.common.util.ClientUtil;
import cn.gson.oasys.dao.roledao.RolepowerlistDao;
import cn.gson.oasys.dao.system.SystemMenuDao;
import cn.gson.oasys.dao.user.UserDao;
import cn.gson.oasys.dao.user.UserLogDao;
import cn.gson.oasys.model.entity.role.Rolemenu;
import cn.gson.oasys.model.entity.system.SystemMenu;
import cn.gson.oasys.model.entity.user.User;
import cn.gson.oasys.model.entity.user.UserLog;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import eu.bitwalker.useragentutils.Version;

@Component
public class RecordInterceptor extends HandlerInterceptorAdapter {
	private final Logger logger = LoggerFactory.getLogger(getClass());

	Tool tool;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		HttpSession session = request.getSession();
		if (!StringUtils.isEmpty(session.getAttribute("userId"))) {
			// 导入dao类
			UserDao udao = Tool.getBean(UserDao.class, request);
			RolepowerlistDao rpdao = Tool.getBean(RolepowerlistDao.class, request);
			Long uid = Long.parseLong(session.getAttribute("userId") + "");
			User user = udao.findById(uid).get();
			List<Rolemenu> oneMenuAll = rpdao.findbyparentxianall(0L, user.getRole().getRoleId(), true, false);
			List<Rolemenu> twoMenuAll = rpdao.findbyparentsxian(0L, user.getRole().getRoleId(), true, false);
			List<Rolemenu> all = new ArrayList<>();
			// 获取当前访问的路径
			String url = request.getRequestURL().toString();
			String zhuan = "notlimit";

			if (oneMenuAll.size() > 0) {
				all.addAll(oneMenuAll);
			}
			if (twoMenuAll.size() > 0) {
				all.addAll(twoMenuAll);
			}
			for (Rolemenu rolemenu : all) {
				if (!rolemenu.getMenuUrl().equals(url)) {

					return true;
				} else {
					request.getRequestDispatcher(zhuan).forward(request, response);
				}

			}

		} else {
			response.sendRedirect("/logins");
		}

		return super.preHandle(request, response, handler);
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		HttpSession session = request.getSession();
		// 导入dao类
		UserDao userDao = Tool.getBean(UserDao.class, request);
		SystemMenuDao systemMenuDao = Tool.getBean(SystemMenuDao.class, request);
		UserLogDao userLogDao = Tool.getBean(UserLogDao.class, request);

		// 获取客户端的IP
		String clientIP = ClientUtil.getClientIp(request);
		logger.debug("客户端的IP为{}", clientIP);

		UserLog uLog = new UserLog();
		String ip = clientIP;
		if (StringUtils.isEmpty(ip)) {
			// 首先就获取ip
			InetAddress ia = null;
			ia = ia.getLocalHost();
			ip = ia.getHostAddress();
		}
		uLog.setIpAddr(ip);

		uLog.setUrl(request.getServletPath());
		uLog.setLogTime(new Date());

		// 还没有登陆不能获取session

		Object obj = session.getAttribute("userId");
		if (null != obj) {
			uLog.setUser(userDao.findById((Long) obj).get());
		} else {
			logger.info("用户未登录，ip为：{}", ip);
		}
		// uLog.setUser(userDao.findOne(1l));
		// 从菜单表里面匹配
		logger.debug("访问路径：{}", request.getServletPath());
		List<SystemMenu> sMenus = (List<SystemMenu>) systemMenuDao.findAll();

		UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
		// 获取浏览器信息
		Browser browser = userAgent.getBrowser();
		Version version = browser.getVersion(request.getHeader("User-Agent"));
		String info = browser.getName() + "/" + version.getVersion();

		uLog.setBrowser(info);
		
		OperatingSystem operatingSystem = userAgent.getOperatingSystem();
		String clientOS = operatingSystem.getName();
		
		uLog.setClientOS(clientOS);
		
		// 登记未登录用户的信息
		boolean existFlag = false;
		for (SystemMenu systemMenu : sMenus) {
			if (systemMenu.getMenuUrl().equals(request.getServletPath())) {
				existFlag = true;
				// 只有当该记录的路径不等于第一条的时候
				if (!userLogDao.findByUserlaset(1l).getUrl().equals(systemMenu.getMenuUrl())) {
					uLog.setTitle(systemMenu.getMenuName());
					// 只要匹配到一个保存咯
					userLogDao.save(uLog);
				}
			}
		}
		if (!existFlag) {
			userLogDao.save(uLog);
		}

		// 如果是用户退出，则将session过期
		String servletPath = request.getServletPath();
		logger.info(servletPath);
		if("/loginout".equalsIgnoreCase(servletPath)){
			if(null != session){
				session.removeAttribute("userId");
				session.setMaxInactiveInterval(1);
			}
		}
	}

}
